
//  ViewController.m
//  Demo
//
//  Created by 龚碧容 on 2017/9/15.
//  Copyright © 2017年 hwd. All rights reserved.
//

#import "ViewController.h"

#import "QLMHomeTableView.h"

#import "QLMAddBaoxiuVC.h"
#import "QLMHotNewsModel.h"

#import "QLMDetailAddressVC.h"
#import "QLMNoticeListVC.h"
#import "AppDelegate.h"

#import "homeData+CoreDataClass.h"
#import "QLMBXOrderDetailVC.h"

@interface ViewController ()<QLMHomeTableViewDelegate>{
    QLMHotNewsArrayModel *hotnewsArraymodel;
    __block NSString *networkStatusStr;
}

@property (nonatomic,strong) QLMHomeTableView *homeTableView;
@property (nonatomic,strong) UIImageView *navBarHairlineImageView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    self.view.backgroundColor=[UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1.00];
    self.title=@"首页";
    
    hotnewsArraymodel=[[QLMHotNewsArrayModel alloc] init];
    hotnewsArraymodel.dataCarouselFigure=[NSArray array];
    hotnewsArraymodel.dataHotNews=[NSArray array];
    hotnewsArraymodel.dataAnnouncement=[NSMutableArray array];
    hotnewsArraymodel.dataAccessories=[NSArray array];
    
    _navBarHairlineImageView = [ClientTool findHairlineImageViewUnder:self.navigationController.navigationBar];
    
    CGRect tableRect = CGRectMake(0, 0, kScreen_width, kScreen_height-49-IOS11_OR_LATER_SPACE(34));
    
    _homeTableView=[[QLMHomeTableView alloc] initWithFrame:tableRect];
    _homeTableView.delegate=self;
    _homeTableView.titleArray=[NSArray arrayWithObjects:@"报修",@"二手机",@"保险",@"职校",nil];//@"保养",
    _homeTableView.imagenameArray=[NSArray arrayWithObjects:@"01_weixiu",@"03_ershouji",@"04_baoxian",@"05_xuexiao", nil];//@"02_baoyang",
    _homeTableView.pjtitleArray=[NSArray arrayWithObjects:@"保养包",@"液压件",@"发动机",@"底盘件",@"斗齿类", nil];
    _homeTableView.pjimagenameArray=[NSArray arrayWithObjects:@"peijian_01",@"peijian_02",@"peijian_03",@"peijian_04",@"peijian_05", nil];
    
    [self.view addSubview:_homeTableView];
    
    if (@available(iOS 11.0, *)) {
        _homeTableView.tableview.contentInsetAdjustmentBehavior=UIScrollViewContentInsetAdjustmentNever;
    } else {
        // Fallback on earlier versions
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    AppDelegate * app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    NSString *pushName = [[app.pushUserInfo objectForKey:@"aps"] objectForKey:@"alert"];
    if([ClientTool isNull:pushName]){
        [self getPushInfo:app.pushUserInfo];
    }
}

- (void)getPushInfo:(NSDictionary *)dict{
    if ([[UserManager sharedManager] isUserLogin]){//判断用户是否登录
        [self requRepairOrder:dict];
    }else{
        QLMLoginViewController *loginController = [QLMLoginViewController new];
        loginController.pushUid=dict[@"userId"];
        loginController.resultBlock=^(BOOL success){};
        QLMCustomNavCtr *nav=[[QLMCustomNavCtr alloc] initWithRootViewController:loginController];
        [self.navigationController presentViewController:nav animated:YES completion:nil];
    }
}

- (void)requRepairOrder:(NSDictionary *)dict{
    NSMutableDictionary *paramerDic=[NSMutableDictionary dictionary];
    [paramerDic setObject:dict[@"repairOrderId"] forKey:@"repairOrderId"];
    [ClientTool postUrlPath:@"/test/repairOrder/orderInfo" withParamers:paramerDic andBody:nil
                    success:^(id responseObject){
                        NSInteger code = [[responseObject objectForKey:@"flag"] integerValue];
                        if (code == 1) {
                            
                            QLMOrderListInfoModel *resultInfoModel=[[QLMOrderListInfoModel alloc] initWithDictionary:responseObject[@"repairOrder"] error:nil];
                            [self pushToOrderDetailVC:resultInfoModel withOrderId:dict[@"repairOrderId"]];
                            
                        }else{
                            ETToast(responseObject[@"msg"]);
                        }
                    }failure:^(NSError *error){
                        ETToast(@"服务器连接失败");
                    }
     ];
}

- (void)pushToOrderDetailVC:(QLMOrderListInfoModel *)resultOrderModel withOrderId:(NSString *)orderId{
    QLMBXOrderDetailVC *messageVC = [QLMBXOrderDetailVC new];
    messageVC.repairOrderId=orderId;
    messageVC.resultInfoModel=resultOrderModel;
    messageVC.isPushJumpBool=YES;
    self.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:messageVC animated:YES];
    self.hidesBottomBarWhenPushed=NO;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self aFNetworkStatus];
    _navBarHairlineImageView.hidden=YES;
    self.navigationController.navigationBarHidden=YES;
    [self requestHomeData];
    
    [MobClick beginLogPageView:self.title];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    _navBarHairlineImageView.hidden=NO;
    [MobClick endLogPageView:self.title];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -
- (void)aFNetworkStatus{
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        NSString *statusInt=nil;
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                statusInt=@"1";
                break;
            case AFNetworkReachabilityStatusNotReachable:
                statusInt=@"2";
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                statusInt=@"3";
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                statusInt=@"4";
                break;
            default:
                break;
        }

        networkStatusStr=statusInt;
        if ([statusInt integerValue]==2) {
            [self updateDataModel:[self query]];
        }
    }];
    [manager startMonitoring];
}

- (void)updateDataModel:(NSDictionary *)dic{
    hotnewsArraymodel.dataCarouselFigure=dic[@"dataCarouselFigure"];
    hotnewsArraymodel.dataHotNews=dic[@"dataHotNews"];
    hotnewsArraymodel.dataAnnouncement=[NSMutableArray arrayWithArray:dic[@"dataAnnouncement"]];
    hotnewsArraymodel.dataAccessories=dic[@"dataAccessories"];
    _homeTableView.hotNewsArrayModel=hotnewsArraymodel;
}

#pragma mark - request HomeData
- (void)requestHomeData{
//    [self.view makeToastActivity:CSToastPositionCenter];
    [ClientTool postUrlPath:@"/rest/homePage/getAll" withParamers:nil andBody:nil
                    success:^(id responseObject){
//                        [self.view hideToastActivity];
                        NSInteger code = [[responseObject objectForKey:@"flag"] integerValue];
                        if (code == 1){
                            NSDictionary *dic=responseObject[@"data"];
                            [self updateDataModel:dic];
                            [self addIntoDataSource:[NSArray arrayWithObject:dic]];
                        }else{
                            ETToast(responseObject[@"msg"]);
                        }
                    }failure:^(NSError *error){
                        [self.view hideToastActivity];
                        ETToast(@"服务器连接失败");
                    }
     ];
}

//插入数据
- (void)addIntoDataSource:(NSArray *)ajsonArray{
    
    AppDelegate *_myAppDelegate=(AppDelegate*)[UIApplication sharedApplication].delegate;
    homeData *user=(homeData *)[NSEntityDescription insertNewObjectForEntityForName:@"Entity" inManagedObjectContext:_myAppDelegate.managedObjectContext];
    [user setHomeInfo:ajsonArray];

    NSError* error;
    BOOL isSaveSuccess=[_myAppDelegate.managedObjectContext save:&error];
    if (!isSaveSuccess) {
        NSLog(@"Error:%@",error);
    }else{
        NSLog(@"保存成功!");
    }
}

//查询
- (NSDictionary *)query{
    NSDictionary *ajsonDic=[NSDictionary dictionary];
    AppDelegate *_myAppDelegate=(AppDelegate*)[UIApplication sharedApplication].delegate;
    NSFetchRequest *request=[[NSFetchRequest alloc] init];
    NSEntityDescription * user=[NSEntityDescription entityForName:@"Entity" inManagedObjectContext:_myAppDelegate.managedObjectContext];
    [request setEntity:user];
    
    NSError *error=nil;
    NSMutableArray* mutableFetchResult=[[_myAppDelegate.managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
    if (mutableFetchResult==nil) {
        NSLog(@"Error:%@",error);
    }
    if ([mutableFetchResult count]!=0) {
        homeData *user=[mutableFetchResult objectAtIndex:0];
        NSArray *ajsonArray=(NSArray *)user.homeInfo;
        ajsonDic=ajsonArray[0];
    }
    return ajsonDic;
}

#pragma mark - Action
- (void)clickNoticeLabel:(NSString *)idStr{
    
    QLMDetailAddressVC *webVC=[QLMDetailAddressVC new];
    webVC.htmlurlStr=[NSString stringWithFormat:@"%@/html/phone/announcementDetails.html?id=%@",kWebShareUrl,idStr];
    webVC.title=@"小马公告";
    self.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:webVC animated:YES];
    self.hidesBottomBarWhenPushed=NO;
}

- (void)_creatButton:(CGRect)aFrame title:(NSString *)aTitle image:(NSString *)imageName{
    UIButton *newButton = [UIButton buttonWithType:UIButtonTypeCustom];
    newButton.frame = aFrame;
    [newButton setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    [newButton setTitle:aTitle forState:UIControlStateNormal];
    [newButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    newButton.backgroundColor = [UIColor lightGrayColor];
    [newButton verticalImageAndTitle:5];
    [self.view addSubview:newButton];
}

- (void)tapImageView:(NSInteger)imageTag{
    
    QLMCarouselFigureModel *carouseModel=[[QLMCarouselFigureModel alloc] initWithDictionary:hotnewsArraymodel.dataCarouselFigure[imageTag] error:nil];
    if ([carouseModel.skipUrl length]==0) {
        return;
    }
    
    NSString *htmlStr=nil;
    if([carouseModel.skipUrl hasPrefix:@"http://"]||[carouseModel.skipUrl hasPrefix:@"https://"]){
        htmlStr=carouseModel.skipUrl;
    }else{
        htmlStr=[NSString stringWithFormat:@"http://%@",carouseModel.skipUrl];
    }
    NSLog(@"htmlStr = %@",htmlStr);
    if ([htmlStr containsString:@"/rest/shop/index"]) {
        [self reuqestWebInfoData];
    }else{
        [self setUpWebVC:nil withHtmlurl:htmlStr];
    }
}

- (void)reuqestWebInfoData{
    if ([[UserManager sharedManager] isUserLogin]) {
        NSString *token=[[NSUserDefaults standardUserDefaults] objectForKey:kLoginToken];
        NSDictionary *tokenDic=[NSDictionary dictionaryWithObjectsAndKeys:token,@"token", nil];
        
        [self.view makeToastActivity:CSToastPositionCenter];
        [ClientTool postUrlPath:@"/rest/shop/index" withParamers:nil andBody:tokenDic
                        success:^(id responseObject){
                            [self.view hideToastActivity];
                            [self setUpWebVC:@"礼品兑换" withHtmlurl:responseObject[@"url"]];
                        }failure:^(NSError *error){
                            [self.view hideToastActivity];
                            ETToast(@"服务器连接失败");
                        }
         ];
    }else{
        ETToast(@"请先登录");
    }
}

- (void)setUpWebVC:(NSString *)titleStr withHtmlurl:(NSString *)urlStr{
    QLMDetailAddressVC *webVC=[QLMDetailAddressVC new];
    webVC.htmlurlStr=urlStr;
    webVC.title=titleStr;
    self.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:webVC animated:YES];
    self.hidesBottomBarWhenPushed=NO;
}

- (void)didselectMore:(NSInteger)moreTag{
    if (moreTag==1000){
        if ([[UserManager sharedManager] isUserLogin]) {//判断是否登录
            [self pushToBaoxiuVC:NO];
        }else{
            [self presentaLoginVC];
        }
    }else if (moreTag==3001){//公告
        QLMNoticeListVC *noticeListVC=[QLMNoticeListVC new];
        noticeListVC.arrayModel=hotnewsArraymodel;
        self.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:noticeListVC animated:YES];
        self.hidesBottomBarWhenPushed=NO;

    }else{
        [self pustWebViewToVC:moreTag];
    }
}

- (void)didselectTopushVC:(NSIndexPath *)indexPath{
    [self pushToWebView:indexPath.row];
}

- (void)presentaLoginVC{
    QLMLoginViewController *loginController = [QLMLoginViewController new];
    loginController.resultBlock=^(BOOL success){};
    QLMCustomNavCtr *nav=[[QLMCustomNavCtr alloc] initWithRootViewController:loginController];
    [self.navigationController presentViewController:nav animated:YES completion:nil];
}

#define mark - pustToNextVC
- (void)pushToBaoxiuVC:(BOOL)isCanEdit{
    QLMAddBaoxiuVC *bxOrderDetailVC=[QLMAddBaoxiuVC new];
    bxOrderDetailVC.isBaoyangDevicebool=isCanEdit;
    self.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:bxOrderDetailVC animated:YES];
    self.hidesBottomBarWhenPushed=NO;
}

- (void)pushToWebView:(NSInteger)row{
    
    if (hotnewsArraymodel.dataHotNews.count!=0) {
 
        QLMHotNewsModel *hotnewsModel=[[QLMHotNewsModel alloc] initWithDictionary:hotnewsArraymodel.dataHotNews[row] error:nil];
        NSString *htmlStr=nil;
        
        if ([hotnewsModel.newsPath length]==0) {
            if(hotnewsModel.hotNewsId.length==0){
                ETToast(@"新闻链接不可用！");
                return;
            }else{
                htmlStr=[NSString stringWithFormat:@"%@/html/phone/newsDetails.html?id=%@",kWebShareUrl,hotnewsModel.hotNewsId];
            }
        }else{
            htmlStr=hotnewsModel.newsPath;
        }
        
        QLMDetailAddressVC *webVC=[QLMDetailAddressVC new];
        webVC.htmlurlStr=htmlStr;
        webVC.title=@"新闻";
        self.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:webVC animated:YES];
        self.hidesBottomBarWhenPushed=NO;
    }
}

- (void)pustWebViewToVC:(NSInteger)row{
    QLMDetailAddressVC *webVC=[QLMDetailAddressVC new];
    NSString *tmpUserid=[NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:kLoginUserId]];
    NSString *userId=nil;
    if (tmpUserid.length==0) {
        userId=@"";
    }else{
        userId=tmpUserid;
    }
    
    switch (row) {
        //好机手 二手机 学技能
        case 1001:
            webVC.htmlurlStr=@"http://ershouji.sevalo.com/ershouji/index.aspx";
            webVC.title=@"二手机";
            break;
        case 1002:
            webVC.htmlurlStr=@"http://beta.sevalo.com/exiaoma_wx/insurancePage/insurance.html";
            webVC.title=@"保险";
            break;
        case 1003:
            webVC.htmlurlStr=@"http://www.qlmzx.com/";
            webVC.title=@"学技能";
            break;
        //整机跳转网页
        case 5460:
            webVC.htmlurlStr=[NSString stringWithFormat:@"%@/html/phone/machine.html?id=%@&userId=%@",kWebShareUrl,@"-3",userId];
            webVC.title=@"土石方机械";
            break;
        case 5461:
            webVC.htmlurlStr=[NSString stringWithFormat:@"%@/html/phone/machine.html?id=%@&userId=%@",kWebShareUrl,@"-4",userId];
            webVC.title=@"路面机械";
            break;
        case 5462:
            webVC.htmlurlStr=[NSString stringWithFormat:@"%@/html/phone/assemblyMachine.html?typeId=%@&userId=%@",kWebShareUrl,@"-5",userId];
            webVC.title=@"再制造机械";
            break;
        //配件跳转
        case 3210:{
            webVC.htmlurlStr=[self resultAccessoriesStr:userId withTypeid:@"1"];
            webVC.title=@"配件展示";
        }
            break;
        case 3211:{
            webVC.htmlurlStr=[self resultAccessoriesStr:userId withTypeid:@"9"];
            webVC.title=@"配件展示";
        }
            break;
        case 3212:{
            webVC.htmlurlStr=[self resultAccessoriesStr:userId withTypeid:@"10"];
            webVC.title=@"配件展示";
        }
            break;
        case 3213:{
            webVC.htmlurlStr=[self resultAccessoriesStr:userId withTypeid:@"11"];
            webVC.title=@"配件展示";
        }
            break;
        case 3214:
        {
            webVC.htmlurlStr=[self resultAccessoriesStr:userId withTypeid:@"12"];
            webVC.title=@"配件展示";
        }
            break;
        //新闻列表网页
        case 2002:
            webVC.htmlurlStr=[NSString stringWithFormat:@"%@/html/phone/news.html",kWebShareUrl];
            webVC.title=@"新闻";
            break;
            
        default:
            break;
    }
    
    self.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:webVC animated:YES];
    self.hidesBottomBarWhenPushed=NO;
}

- (NSString *)resultAccessoriesStr:(NSString *)tmpUserId withTypeid:(NSString *)typeId{
    NSString *accessoriesStr=@"/html/phone/accessories.html?typeId=";
    NSString *htmlStr=[NSString stringWithFormat:@"%@%@%@&userId=%@",kWebShareUrl,accessoriesStr,typeId,tmpUserId];
    return htmlStr;
}

@end
